package com.changgou.filter;

import com.changgou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.print.attribute.standard.RequestingUserName;

/**
 * @Author: wzw
 * @Date: 2020/12/20 20:03
 * @version: 1.8
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    // 定义常量-Oauth2.0官网中token的key
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * @param exchange 响应,
     * @param chain    链表:是否放行
     * @return reactor.core.publisher.Mono<java.lang.Void>
     * @author wzw
     * 业务处理
     * @Date 20:06 2020/12/20
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request,response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.判断用户是否登录操作,如果是,则直接放行
        //获取用户请求路径
        String url = request.getURI().getPath();
        //判断是否登录
        if (url.startsWith("/api/user/login")) {
            //放行
            return chain.filter(exchange);
        }

        // 2.其他请求,需要判断用户是否登录（判断用户是否携带token信息）,三种方式都判断
        // 2.1 从请求参数获取token
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        // 非空判断
        if (StringUtils.isEmpty(token)) {
            // 2.2 从请求头获取token
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        }
        // 非空判断
        if (StringUtils.isEmpty(token)) {
            // 2.3 从cookie中获取token
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            //判断是否有cookie
            if (cookie != null) {
                //获取cookie的值
                token = cookie.getValue();
            }
        }

        // 3、如果没有token，不放行
        if (StringUtils.isEmpty(token)) {
            //设置响应状态码,401无效认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 提交内容
            return response.setComplete();
        }

        try {
            // 4、token存在，需要解析token
//            Claims claims = JwtUtil.parseJWT(token);
            //手动添加头信息(调用其他微服务,需要走网关,因此我们将token添加到头信息中)
            request.mutate().header(AUTHORIZE_TOKEN, "bearer " + token);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败:设置响应状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //提交
            return response.setComplete();
        }
        //5.解析成功:放行
        return chain.filter(exchange);
    }

    /**
     * @author wzw
     * 过滤器执行顺序
     * @Date 20:35 2020/12/20
     * @param
     * @return int
    **/
    @Override
    public int getOrder() {
        return 0;
    }
}
